<?php

/**
 * Installation script
 *
 * @version $Id$
 * @copyright 2010
 */

session_start();

$_SESSION['install_stage'] = $_GET['stage'];

switch($_SESSION['install_stage'])
{
	case 2: //database settings
		$stage = '2/6';
		$title = 'Database settings';
		$content = '<p>Please fill in this form for connection to your MySQL database. Yaps! works only with MySQL database.</p>
								<form action="index.php?stage=3" method="post">
								<table cellspacing="1">
									<tr><td>Server</td><td><input type="text" name="server" /></td>
									<td class="small">Address of your server, usually something like <i>localhost</i></td></tr>
									<tr><td>Username</td><td><input type="text" name="user" /></td>
									<td class="small">Username for your database</td></tr>
									<tr><td>Password</td><td><input type="password" name="password" /></td>
									<td class="small">Password for your database</td></tr>
									<tr><td>Database name</td><td><input type="text" name="dbname" /></td>
									<td class="small">Name of your database</td></tr>
									<tr><td colspan="3"><input type="submit" value="Test database connection" /></td></tr>
								</table>
								</form>';
	break;
	case 3:
		$stage = '3/6';
		$title = 'Database connection';
		$content = 'Trying to connect to your MySQL DB...';

		$db_server = $_POST['server'];
		$db_name = $_POST['dbname'];
		$db_user = $_POST['user'];
		$db_pass = $_POST['password'];

		@$connect = mysql_connect($db_server,$db_user,$db_pass);
		if($connect)
		{
			$content .= '<span class="ok">OK</span><br />';
		}
		else
		{
			$content .= '<span class="err">Error</span><br />';
			$err = true;
		}

		if(!$err)
		{
			$content .= 'Trying to select DB with name '.$db_name.'...';
			@$select = mysql_select_db($db_name);
			if($select)
			{
				$content .= '<span class="ok">OK</span><br />';
			}
			else
			{
				$content .= '<span class="err">Error</span><br />';
				$err_select = true;
			}

			if(!$err_select)
			{
				$content .= 'Creating config.php in root of Yaps!...';

				$config_php = '<?php

/**
 * Configuration file, DB connection
 */

// ------------------------------------------------
// Database
// ------------------------------------------------

$dbuser = "'.$db_user.'";

$dbpassword = "'.$db_pass.'";

$dbname = "'.$db_name.'";

$dbserver = "'.$db_server.'";

// ------------------------------------------------
/// CONNECTION TO MYSQL DB AND DATABASE SELECTION
// ------------------------------------------------

$conn=MySQL_Connect($dbserver, $dbuser , $dbpassword);
if (!$conn):
	die("Error in connection: ".mysql_error());
endif;

$vyberdb=MySQL_Select_DB($dbname);
if (!$vyberdb):
	die("DB selection error: ".mysql_error());
endif;

// ------------------------------------------------
// Constants
// ------------------------------------------------

$query = mysql_query("SELECT * FROM yaps_config");
while($row = mysql_fetch_array($query))
{
	$name = strtoupper($row[\'name\']);
	define($name,$row[\'value\']);
}

?>';

				$file = fopen('../config.php','w');
				if(!$file)
				{
					$content .= '<span class="err">Error, cant create config.php file, <a href="http://en.wikipedia.org/wiki/Chmod">chmod</a> your Yaps! root to 777 and refresh this page OR create config.php manualy a insert this inside.</span><br />';
					$content .= '<pre>'.nl2br(htmlspecialchars($config_php)).'</pre>';
				}
				else
				{
					fwrite($file,$config_php);
					fclose($file);
					$content .= '<span class="ok">OK</span><br />';
				}

				$content .= '<p>If you are using <i>Uploadify plugin</i>, make sure that you have <b>chmoded /uploads dir to 777!</b></p>';
				$content .= '<p>If you are using <i>Gallery plugin</i>, make sure that you have <b>chmoded /gallery dir to 777!</b></p>';

				$content .= '<span class="ok"><a href="index.php?stage=4">Everything si fine, lets populate your DB</a></span>';
				$_SESSION['db_info']['server'] = $db_server;
				$_SESSION['db_info']['user'] = $db_user;
				$_SESSION['db_info']['pass'] = $db_pass;
				$_SESSION['db_info']['name'] = $db_name;
			}
			else
			{
				$content .= '<span class="err">Error: Could not select your database '.$db_name.'. Please enter valid username, password, server and DB name. <a href="index.php?stage=2">Try it again</a></span>';
			}
		}
		else
		{
			$content .= '<span class="err">Error: Could not connect to your database. Please enter valid username, password, server and DB name. <a href="index.php?stage=2">Try it again</a></span>';
		}

	break;
	case 4:
		$stage = '4/6';
		$title = 'Populating your DB';

		$connect = mysql_connect($_SESSION['db_info']['server'],$_SESSION['db_info']['user'],$_SESSION['db_info']['pass']);
		$select = mysql_select_db($_SESSION['db_info']['name']);

		$create_table = mysql_query('CREATE TABLE IF NOT EXISTS `yaps_config` (
		   `name` varchar(255) COLLATE utf8_czech_ci NOT NULL,
		   `value` text COLLATE utf8_czech_ci NOT NULL,
		   PRIMARY KEY (`name`)
		   ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci');

		$create_table_2 = mysql_query('CREATE TABLE IF NOT EXISTS `yaps_menu` (
			  `id` int(11) NOT NULL AUTO_INCREMENT,
			  `name` text COLLATE utf8_czech_ci NOT NULL,
			  `link` text COLLATE utf8_czech_ci NOT NULL,
			  `position` int(11) NOT NULL,
			  PRIMARY KEY (`id`)
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci AUTO_INCREMENT=0');

		$create_table_3 = mysql_query('CREATE TABLE IF NOT EXISTS `yaps_admin` (
			  `id` int(11) NOT NULL AUTO_INCREMENT,
			  `username` text COLLATE utf8_czech_ci NOT NULL,
			  `password` text COLLATE utf8_czech_ci NOT NULL,
			  PRIMARY KEY (`id`)
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_czech_ci AUTO_INCREMENT=0');

		$create_table_4 = mysql_query('CREATE TABLE IF NOT EXISTS `yaps_routing_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `url` text CHARACTER SET utf8 COLLATE utf8_czech_ci NOT NULL,
  `plugin` text CHARACTER SET utf8 COLLATE utf8_czech_ci NOT NULL,
  `action` text CHARACTER SET utf8 COLLATE utf8_czech_ci NOT NULL,
  `id_for_action` text CHARACTER SET utf8 COLLATE utf8_czech_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=ucs2 COLLATE=ucs2_czech_ci AUTO_INCREMENT=0;');

		$query = mysql_query('TRUNCATE `yaps_admin`');
		$query = mysql_query('TRUNCATE `yaps_config`');
		$query = mysql_query('TRUNCATE `yaps_menu`');

		$insert_data = mysql_query("INSERT INTO `yaps_config` (`name`, `value`) VALUES
		   ('default_plugin', 'blog'),
		   ('default_theme', 'earthlingtwo'),
		   ('core_dir', 'core/'),
		   ('plugins_dir', 'plugins/'),
		   ('themes_dir', 'themes/'),
		   ('js_dir', 'script/'),
		   ('uploads_dir', 'uploads/'),
		   ('file_info', 'plugin_info.php'),
		   ('file_plugin_class', 'class_'),
		   ('file_plugin_actions', 'actions_'),
		   ('file_theme_info', 'theme_info.php')");

		$insert_data_2 = mysql_query("INSERT INTO `yaps_menu` (`id`, `name`, `link`, `position`) VALUES
				(1, 'Admin', 'admin', 1),
				(2, 'Home', '.', 2)");

		if($create_table && $create_table_2 && $create_table_3 && $create_table_4 && $insert_data && $insert_data_2)
		{
			$content = '<span class="ok"><a href="index.php?stage=5">Success! You can continue to next stage, where we will set up your page title and description</a><br /></span>
Your default plugin is <b>Blog</b> and defaut theme is <b>earthlingtwo</b>. You can change this later in administration, so make sure that you have at least earthlingtwo theme for first run.';
		}
		else
		{
			$content = '<span class="err">Oops, cant insert data in your database, check database rights of user `'.$_SESSION['db_info']['user'].'` for database `'.$_SESSION['db_info']['name'].'`. <a href="index.php?stage=3">Try it again!</a></span>';
		}
	break;
	case 5:
		$stage = '5/6';
		$title = 'Your own settings';
		$content = '<p>In this stage, you will add your very own settings of your Yaps!</p>
								<form action="index.php?stage=6" method="post">
								<table cellspacing="1">
									<tr><td>Page name</td><td><input type="text" name="page_name" /></td>
									<td class="small">Name of your page, for example: <i>Pirozek`s new site</i></td></tr>
									<tr><td>Page description</td><td><input type="text" name="page_desc" /></td>
									<td class="small">Description of your page, for example: <i>My page about me</i></td></tr>
									<tr><td>Page URL</td><td><input type="text" name="page_url" /></td>
									<td class="small">Full URL of your page <b>ending with slash</b>, for example: <i>http://pirozek.mafyje.com/yaps/</i></td></tr>
									<tr><td>Password salt</td><td><input type="text" name="salt" /></td>
									<td class="small"><a href="http://en.wikipedia.org/wiki/Salt_%28cryptography%29">Salt</a> for security, if you dont know what to write here, just insert some mambo jambo longer than 5 chars :)</td></tr>
									<tr><td>Admin name</td><td><input type="text" name="admin_name" /></td>
									<td class="small">Username for your Yaps! admin account, for example: <i>admin</i></td></tr>
									<tr><td>Admin password</td><td><input type="password" name="admin_pass" /></td>
									<td class="small">Admin account password, it should contain at least one number and one special char (#$%^&*!)</td></tr>
									<tr><td colspan="3"><input type="submit" value="Use my settings" /></td></tr>
								</table>
								</form>';
	break;
	case 6:
		$stage = '6/6';
		include '../config.php';
		$title = 'Tadaaaaa :)';

		$query = mysql_query("INSERT INTO yaps_config VALUES
													('page_name','".$_POST['page_name']."'),
													('page_desc','".$_POST['page_desc']."'),
													('web_url','".$_POST['page_url']."'),
													('salt','".$_POST['salt']."')");

		$query_2 = mysql_query("INSERT INTO yaps_admin VALUES
														('0','".$_POST['admin_name']."','".md5($_POST['admin_pass'].$_POST['salt'])."')");

		if($query && $query_2)
		{
			$content = '<span class="ok">Everything is fine, you can use your Yaps! now. Dont worry about installing plugins, just copy them into plugins/ directory, they will be installed automaticaly for you.</span><br />
								<strong>Just one more thing, <span class="err">delete this install/ directory, or at least rename it</span>, or anyone with basic knowledge of Yaps! can change your admin password and destroy your web.</strong><br />
								<a href="'.$_POST['page_url'].'">Take me to my homepage</a>';
		}
		else
		{
			$content = '<span class="err">Oops, cant insert your settings in DB, please check your database settings and <a href="index.php">re-run this install script</a></span>';
		}


	break;
	case 1: //intro
	default:
		$stage = '1/6';
		$php_version = explode('.',phpversion());
		if($php_version[0] > 4)
		{
			$php_status = '<span class="ok">'.phpversion().'</span>';
		}
		else
		{
			$php_status = '<span class="bad">'.phpversion().'</span>';
			$err = 'Oops, you dont meet all of our requirements :( Installation canceled.';
		}

		$title = 'Intro';
		$content = 'Hi and welcome to install script pro PHP plugin system Yaps!<br />
								We will do a little check, if your hosting / server meets our requirements.<br /><br />
								PHP 5+ => '.$php_status.'<br />
								Good star constelation => <span class="ok">OK</span><br />
								Happy mood => <span class="ok">Good</span><br /><br />';

		if(strlen($err) > 0)
		{
			$content .= '<span class="bad">'.$err.'</span>';
		}
		else
		{
			$content .= '<span class="ok"><a href="index.php?stage=2">Everything is fine, lets install Yaps!</a></span>';
		}

		break;
}

echo '
<!DOCTYPE html
	PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	<html lang="en">
	<head>

	<link rel="stylesheet" type="text/css" href="style.css" />

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

	<title>Yaps! Installation script - ',$title,'</title>

	</head>

	<body>

	<div id="wrapper">

		<h1>Yaps! Install script - ',$title,'</h1>
		<div id="content">
		',$content,'
		</div>

	</div>

	<div class="footer">Current stage of installation process: <strong>',$stage,'</strong></div>

	</body>

	</html>';

?>